package com.hisan.freeride.home.activity;

import android.content.Intent;
import android.os.Bundle;
import android.text.Editable;

import com.alibaba.sdk.android.push.CommonCallback;
import com.blankj.utilcode.util.LogUtils;
import com.google.gson.Gson;
import com.hisan.freeride.R;
import com.hisan.freeride.common.base.AppConfig;
import com.hisan.freeride.common.base.BaseActivity;
import com.hisan.freeride.common.base.BaseAppLication;
import com.hisan.freeride.common.callback.DialogCallback;
import com.hisan.freeride.common.listener.IEditTextChangeListener;
import com.hisan.freeride.common.utils.CacheUtils;
import com.hisan.freeride.common.utils.CollectionUtils;
import com.hisan.freeride.common.utils.GsonUtils;
import com.hisan.freeride.common.utils.WorksSizeCheckUtil;
import com.hisan.freeride.databinding.LoginBinding;
import com.hisan.freeride.home.model.Code;
import com.hisan.freeride.home.model.LoginModel;
import com.lzy.okgo.OkGo;

import org.json.JSONException;
import org.json.JSONObject;


/**
 * 创建时间 : 2017/6/5
 * 创建人：yangyingqi
 * 公司：嘉善和盛网络有限公司
 * 备注：登入页面
 */
public class LoginActivity extends BaseActivity<LoginBinding>  {
    private Intent intent;
    @Override
    protected int getLayoutId() {
        return R.layout.login;
    }

    @Override
    protected void initView() {
        mBinding.loginOk.setEnabled(false);
//        EventBus.getDefault().register(this);
        mBinding.selectXy.setOnClickListener(v -> RotationActivity.skip(LoginActivity.this, AppConfig.agreement));

        //1.创建工具类对象 把要改变颜色的Button先传过去
        WorksSizeCheckUtil.textChangeListener textChangeListener = new WorksSizeCheckUtil.textChangeListener(mBinding.loginOk);
        //2.把所有要监听的edittext都添加进去
        textChangeListener.addAllEditText(mBinding.username);
        //3.接口回调 在这里拿到boolean变量 根据isHasContent的值决定 tv 应该设置什么颜色
        WorksSizeCheckUtil.setChangeListener(new IEditTextChangeListener() {
            @Override
            public void textChange(boolean isHasContent) {
                if(isHasContent){
                    mBinding.loginOk.setEnabled(true);
                }else{
                    mBinding.loginOk.setEnabled(false);
                }
            }
            @Override
            public void afterChange(Editable editable) {
            }
        });

    }

    @Override
    protected void initEvent() {
        mBinding.check.setOnCheckedChangeListener((buttonView, isChecked) -> {
            if(isChecked){
                mBinding.loginOk.setEnabled(true);
            }else{
                mBinding.loginOk.setEnabled(false);
            }
        });
        mBinding.topBack.setOnClickListener(v -> {
            Intent intent=new Intent();
            setResult(99,intent);
            finishActivity(true);
        });

        mBinding.loginOk.setOnClickListener(v -> {
            String  name=mBinding.username.getText().toString();
            String pass=mBinding.pass.getText().toString();
            if (CollectionUtils.isNullOrEmpty(name)||CollectionUtils.isNullOrEmpty(pass)){
                showToast("缺乏参数");
                return;
            }
            Login(name,pass);
        });
        mBinding.password.setOnClickListener(v -> startActivityForResult(PaasWordActivity.class,99,null,true));
        mBinding.register.setOnClickListener(v -> startActivityForResult(RegisterActivity.class,99,null,true));
    }

    //登入
    private void Login(final String name, String pass){
        OkGo.post(AppConfig.LoginUrl)
                .tag(this)
                .params("mobile",name)
                .params("password",pass)
                .execute(new DialogCallback<Object>(this){
                    @Override
                    public void onSuccess(com.lzy.okgo.model.Response<Object> response) {
                        super.onSuccess(response);
                        if (!CollectionUtils.isNullOrEmpty(response.body())){
                            if (isOk(response)){
                                BaseAppLication.getInstance().setIslogin(true);

                                try {
                                    JSONObject object=new JSONObject(response.body().toString());
                                    String token=object.getString("access_token");
                                    CacheUtils.getInstance().put("token",token);
                                    if (CollectionUtils.isNullOrEmpty(intent)){
                                        intent=new Intent();
                                    }
                                    setResult(99,intent);
                                    finishActivity(true);
                                } catch (JSONException e) {
                                    e.printStackTrace();
                                }
                            }else {
                                showError(response);
                            }
                        }
                    }

                    @Override
                    public void onError(com.lzy.okgo.model.Response<Object> response) {
                        super.onError(response);
                        showError(response);
                    }
                });
    }

//    //微信登入回调
//    @Subscribe(threadMode = ThreadMode.MAIN) //在ui线程执行
//    public void onDataSynEvent(WeChatInfo event) {
//        dismissDialog();
//        LogUtils.v("xxx",event.toString());
//        if (!CollectionUtils.isNullOrEmpty(event)){
//            wechat(event);
//        }else {
//            showToast("微信登入失败，请重新登入");
//        }
//    }
//
//    //微信登入
//    private void wechat(WeChatInfo event) {
//        HttpParams params=new HttpParams();
//        params.put("nickname",event.getNickname());
//        params.put("unid",event.getUnionid()+"");
//        params.put("avatar",event.getHeadimgurl());
//        params.put("sex",event.getSex());
//        LogUtils.v("xxx",params.toString());
//        OkHttpUtils.post(AppConfig.Wechat)
//                .tag(this)
//                .params(params)
//                .execute(new DialogCallback<WxLogin>(this) {
//                    @Override
//                    public void onResponse(boolean isFromCache, WxLogin response, Request request, @Nullable Response response2) {
//                        if (!CollectionUtils.isNullOrEmpty(response)){
//                            String  phone="";
//                            LoginModel loginModel=new LoginModel();
//                            loginModel.setNickname(response.getNickname());
//                            loginModel.setAvatar(response.getAvatar());
//                            CacheUtils.getInstance().put("avatar",loginModel.getAvatar());
//                            loginModel.setAccess_token(response.getAccess_token());
//                            CacheUtils.getInstance().put("token",response.getAccess_token());
//                            if (CollectionUtils.isNullOrEmpty(response.getMobile())){
//                                phone="";
//                                loginModel.setMobile(phone);
//                            }else{
//                                loginModel.setMobile(response.getMobile()+"");
//                            }
//                            loginModel.setScore(response.getScore());
//                            CacheUtils.getInstance().put("recommend",response.getRecommend());
//                            TokenManger tokenManger=BaseAppLication.getInstance().getTokenManger();
//                            if (tokenManger.queryAllUser().getCount()>0){
//                                tokenManger.claer();
//                                tokenManger.insert(loginModel);
//                            }else{
//                                tokenManger.insert(loginModel);
//                            }
//                            tokenManger.close();
//                            if (CollectionUtils.isNullOrEmpty(response.getMobile())){
//                                com.hisan.common.view.AlertDialog.Builder builder = new com.hisan.common.view.AlertDialog.Builder(LoginActivity.this);
//                                builder.setTitle("绑定手机号")
//                                        .setMessage("请前往绑定手机号")
//                                        .setTopImage(R.mipmap.certification_prompt)
//                                        .setNegativeButton("取消", (dialog2, which) -> {
//                                            tokenManger.claer();
//                                            mDialog.dismiss();
//                                        })
//                                        .setPositiveButton("确定", (dialog, which) -> {
//                                            startActivityForResult(BindActivity.class,99,null);
//                                            finishActivity();
//                                        });
//                                mDialog = builder.create();
//                                mDialog.show();
//                            }else{
//                                if (CollectionUtils.isNullOrEmpty(intent)){
//                                    intent=new Intent();
//                                }
//                                setResult(99,intent);
//                                finishActivity();
//                            }
//                        }
//                    }
//
//                    @Override
//                    public void onError(boolean isFromCache, Call call, @Nullable Response response, @Nullable Exception e) {
//                        super.onError(isFromCache, call, response, e);
//                        try {
//                            if (!CollectionUtils.isNullOrEmpty(response)){
//                                JSONObject jsonObject=new JSONObject(response.body().string());
//                                if (!CollectionUtils.isNullOrEmpty(jsonObject)){
//                                    String  msg= jsonObject.getString("msg");
//                                    if (!CollectionUtils.isNullOrEmpty(msg))
//                                        showToast(msg);
//                                }
//                            }
//                        } catch (IOException e1) {
//                            e1.printStackTrace();
//                        } catch (JSONException e1) {
//                            e1.printStackTrace();
//                        }
//                    }
//                });
//    }


    //    /**
//     * 微信登录
//     */
//    private void setWXLogin() {
//        showDialog();
//        WxShareAndLoginUtils.WxLogin();
//    }
    @Override
    protected void loadData(boolean isRefresh) {}
}
